import { Injectable } from '@angular/core';
import { AlertController, ToastController } from 'ionic-angular';

/*
  弹出层
*/
@Injectable()
export class AlertProvider {
  constructor (
    private _alert: AlertController,
    private _toast: ToastController
  ){}

  /**
   * 效果类似于浏览器对象中的 alert 方法
   * @param params AlertOptions alert 参数
   */
  alert (params: AlertOptions) {
    let __alert = this._alert.create({
      title: params.title,
      message: params.message,
      buttons: ['确定']
    });
    __alert.present();
  }

  /**
   * 效果类似于浏览器对象中的 confirm 方法
   * @param params ConfirmOptions 参数
   */
  confirm (params: ConfirmOptions) {
    let __alert = this._alert.create({
      title: params.title,
      message: params.message,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            if (params.cancel) params.cancel();
          }
        },
        {
          text: '确定',
          handler: () => {
            if (params.ok) params.ok();
          }
        }
      ]
    });
    __alert.present();
  }


  msg (options: MsgOptions | string) {
    let opt:MsgOptions = {
      content: typeof options === 'string' ?options : options.content
    };
    if (typeof options === 'object') {
      opt.duration = options.duration ? options.duration : 3000;
      opt.position = options.position ? options.position : 'bottom'
    }

    let toast = this._toast.create({
      message: opt.content,
      duration: opt.duration ? opt.duration : 3000,
      position: opt.position ? opt.position : 'bottom'
    });
    toast.present();

    return toast;
  }
}

export interface AlertOptions {
  title: string,
  message: string,
}

export interface ConfirmOptions {
  title: string,
  message: string,
  ok?: Function,
  cancel?: Function
}

export interface MsgOptions {
  content: string,
  duration?: number,
  position?: 'top' | 'middle' | 'bottom'
}
